#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#define CPS 10 //每秒钟传输的字符个数为10个
#define BUFSIZE CPS
#define BURST 100

static volatile int token = 0;

static void alarm_handler(int s)
{
	alarm(1);	
	token++;
	if(token> BURST){
			token = BURST;
	}
}

int main(int argc,char **argv)
{

		int sfd,dfd;
		int len, red;
		char buf[BUFSIZE];
		if(argc<2){
				fprintf(stderr,"Usage......\n");
				exit(1);
		}		


		signal(SIGALRM,alarm_handler);
		alarm(1);

		sfd  =	open(argv[1],O_RDONLY);
		if(sfd < 0)
		{

				perror("open()");
				exit(1);
		}

		dfd = 1; 

		while(1)
		{

				while(token <= 0)//loop 的值变成1 会死循环，无法继续读
						pause();
				
				token--;

				len = read(sfd,buf,BUFSIZE);
				if(len < 0){
						perror("read()");
						break;
				}	
				if(len == 0){
						break;
				}	

				red = write(dfd,buf,len);
				if (red < 0)
				{

						perror("write()");
						break;	
				}


		}


		close(sfd);
		close(dfd);

		exit(0);
}
